<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" v-for="item in statistics" :key="item.key">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :class="item.iconClass">
              <i :class="item.icon"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-title">{{ item.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>设备状态列表</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">刷新</el-button>
          </div>
          <el-table :data="deviceList" style="width: 100%">
            <el-table-column prop="deviceId" label="设备ID" min-width="150"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastActive" label="最后活动时间" width="180">
              <template slot-scope="scope">
                {{ parseTime(scope.row.lastActive) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleControl(scope.row)">控制</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="'控制设备: ' + currentDevice" :visible.sync="controlDialogVisible" width="30%">
      <el-form :model="controlForm" label-width="80px">
        <el-form-item label="控制命令">
          <el-input v-model="controlForm.command" placeholder="请输入控制命令"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="controlDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendCommand">发送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getDashboardData, sendDeviceCommand, batchSendDeviceCommand} from '@/api/smart/device'

export default {
  name: 'DeviceDashboard',
  data() {
    return {
      statistics: [
        {key: 'total', title: '总设备数', value: 0, icon: 'el-icon-monitor', iconClass: 'total'},
        {key: 'online', title: '在线设备', value: 0, icon: 'el-icon-success', iconClass: 'online'},
        {key: 'offline', title: '离线设备', value: 0, icon: 'el-icon-error', iconClass: 'offline'},
        {key: 'onlineRate', title: '在线率', value: '0%', icon: 'el-icon-data-line', iconClass: 'rate'}
      ],
      deviceList: [],
      selectedDevices: [],
      deviceOptions: [],
      controlDialogVisible: false,
      currentDevice: '',
      controlForm: {
        command: ''
      },
      batchControlForm: {
        command: ''
      },
      refreshTimer: null
    }
  },
  computed: {
    formattedDevices() {
      return this.deviceList.map(device => ({
        key: device.deviceId,
        label: `${device.deviceId} (${device.status ? '在线' : '离线'})`,
        disabled: false
      }))
    }
  },
  watch: {
    deviceList: {
      immediate: true,
      handler(newVal) {
        this.deviceOptions = newVal.map(device => ({
          key: device.deviceId,
          label: `${device.deviceId} (${device.status ? '在线' : '离线'})`,
          disabled: false
        }))
      }
    }
  },
  mounted() {
    this.loadData()
    this.refreshTimer = setInterval(() => {
      this.loadData()
    }, 30000)
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
    }
  },
  methods: {
    loadData() {
      getDashboardData().then(response => {
        const data = response.data //.statistics

        // 计算统计信息
        const total = data.statistics.total // Object.keys(data).length
        const online = data.statistics.online // Object.values(data).filter(status => status).length
        const offline = total - online
        const onlineRate = total > 0 ? (online / total * 100).toFixed(2) + '%' : '0%'

        // 更新统计信息
        this.statistics[0].value = total
        this.statistics[1].value = online
        this.statistics[2].value = offline
        this.statistics[3].value = onlineRate

        console.log("===========", data)
        // 更新设备列表
        this.deviceList = Object.keys(data.deviceStatus).map(deviceId => ({
          deviceId,
          status: data.deviceStatus[deviceId],
          lastActive: Date.now()
        }))
        console.log("===========", this.deviceList)
      })
    },
    refreshData() {
      this.loadData()
      this.$message.success('数据已刷新')
    },
    handleControl(device) {
      this.currentDevice = device.deviceId
      this.controlForm.command = ''
      this.controlDialogVisible = true
    },
    sendCommand() {
      if (!this.controlForm.command) {
        this.$message.warning('请输入控制命令')
        return
      }

      sendDeviceCommand(this.currentDevice, this.controlForm.command).then(() => {
        this.$message.success('命令已发送')
        this.controlDialogVisible = false
      })
    },
    handleBatchControl() {
      if (this.selectedDevices.length === 0) {
        this.$message.warning('请选择要控制的设备')
        return
      }

      if (!this.batchControlForm.command) {
        this.$message.warning('请输入控制命令')
        return
      }

      const deviceCommands = {}
      this.selectedDevices.forEach(deviceId => {
        deviceCommands[deviceId] = this.batchControlForm.command
      })

      batchSendDeviceCommand(deviceCommands).then(() => {
        this.$message.success('批量命令已发送')
        this.batchControlForm.command = ''
        this.selectedDevices = []
      })
    },
    handleSelectByStatus(online) {
      this.selectedDevices = this.deviceList
        .filter(device => device.status === online)
        .map(device => device.deviceId)

      this.$message.success(`已选择所有${online ? '在线' : '离线'}设备`)
    }
  }
}
</script>

<style scoped>
.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 28px;
  color: white;
}

.stat-icon.total {
  background-color: #409EFF;
}

.stat-icon.online {
  background-color: #67C23A;
}

.stat-icon.offline {
  background-color: #F56C6C;
}

.stat-icon.rate {
  background-color: #E6A23C;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-title {
  color: #909399;
  font-size: 14px;
}
</style>
